import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 功能描述:
 * 作者: LDL
 * 创建时间: 2014/8/10 17:55
 */
@ServerEndpoint("/chatRoomServer")
public class MessageEndPoint {

    private static final ArrayList<Session> sessions;

    static {
        sessions = new ArrayList<Session>();
    }

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
    }

    @OnMessage
    public void onMessage(String message) {
        sendMessage(message);
    }

    @OnClose
    public void onClose(Session session,CloseReason closeReason) {
        sessions.remove(session);
        sendMessage(closeReason.getReasonPhrase());
    }

    private void sendMessage(String message){
        for(Session session : sessions){
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

